package com.csap.framework.oauth2.server.service.impl;

import cn.dev33.satoken.SaManager;
import com.csap.framework.core.factory.impl.AbstractCsService;
import com.csap.framework.oauth2.IUserDataCache;
import com.csap.framework.oauth2.server.dao.UserPermissionsDao;
import com.csap.framework.oauth2.server.dao.model.UserPermissionsDAO;
import com.csap.framework.oauth2.server.service.UserPermissionsService;
import com.csap.framework.oauth2.server.service.model.UserPermissionsDTO;
import com.csap.framework.redis.RedisUtil;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * <p>
 * 用户独立拥有的权限
 * </p>
 *
 * @author yangchengfu
 * @dateTime 2023-11-22 22:56:44
 */
@Slf4j
@Service
public class UserPermissionsServiceImpl extends AbstractCsService<UserPermissionsDTO, UserPermissionsDAO, UserPermissionsDao, Long> implements IUserDataCache, UserPermissionsService {
    @Getter
    @Resource
    private RedisUtil redisUtil;

    @Override
    public Set<String> permissions(String userId) {
        return getUserPermissions(userId, key -> {
            Set<String> permissions = findOne(UserPermissionsDTO.builder().userId(userId).build()).map(UserPermissionsDTO::getPermissions).orElseGet(Sets::newHashSet);
            redisUtil.hset(key, userId, permissions, SaManager.getConfig().getCache().getPermissionsTime());
            return permissions;
        });
    }
}
